package com.day1;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.Charset;
import java.util.Date;

public class FirstClientHandler extends ChannelInboundHandlerAdapter {

    //channelAcitve:在客户端连接的时候调用
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        //写入数据给服务器
        ByteBuf input = getByteBuf(ctx);

        ctx.channel().writeAndFlush(input);
    }

    //channelRead:收到数据后都会调用此方法
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //接收服务器返回的信息,msg是Netty读写的载体
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println(new Date()+":客户端接收到服务器的信息："+byteBuf.toString(Charset.forName("utf-8")));
    }

    private ByteBuf getByteBuf(ChannelHandlerContext ctx){
        byte[] bytes = "客户端发送消息:awsl".getBytes(Charset.forName("utf-8"));
        /**
         * ctx.alloc():获取ByteBuf的内存管理器
         */
        ByteBuf buffer = ctx.alloc().buffer();
        buffer.writeBytes(bytes);
        return buffer;
    }
}
